<?php
declare (strict_types = 1);

namespace app\middleware\api;

use Exception;
use app\api\service\serv\ClientService;

class SignAuth
{
    protected $client;
    public function __construct(ClientService $client)
    {
        $this->client = $client;
    }

    /***
     * @param $request
     * @param \Closure $next
     * @return mixed
     * @Author Vee7
     * @Date 2021/12/22
     * @Time 14:25
     * @Description 公共接口签名校验中间件（无需登录且要防止恶意调用的接口）
     */
    public function handle($request, \Closure $next)
    {
        //数据格式demo:
//        $data = [
//            'client_uname' => 1, //授权账户
//            'sign' => 'xxxxxxxxxxx', //签名
//            'randomstr' => 'asijfscd', //随机字符串
//            'data' => ['id' => 1,'title'=>'数据1']
//
//        ];
        //验证数据也可以更改为从header头获取，前端也需要做相应更改
        $dataArray = request()->param();

        //判断是否存在校验内容
        if(!array_key_exists('client_uname',$dataArray) || !array_key_exists('sign',$dataArray) || !array_key_exists('randomstr', $dataArray)){
            return json(['message'=>'非法请求，请检查请求配置','code'=>10011]);
        }
        //校验签名
        $server_sign = $this->client->checkSign($dataArray['sign'],$dataArray['randomstr'],$dataArray['client_uname']);
        if($server_sign != $dataArray['sign']){
            return json(['message'=>'签名校验失败,请检查应用授权','code'=>10010]);
        }
        return $next($request);
    }
}
